package server.service;

import com.qqcommon.Message;
import com.qqcommon.MessageType;
import com.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * @author wty
 * @date 2022/10/27 14:52
 * <p>
 * 给所有人推送新闻消息
 */
public class SendNewsToEveryone implements Runnable {
    @Override
    public void run() {

        // 为了可以推送多次，使用while循环
        while (true) {

            System.out.println("请输入服务器要推送的新闻,(exit停止推送)");
            String news = Utility.readString(1000);
            if ("exit".equals(news)) {
                System.out.println("推送新闻线程退出");
                break;
            }
            Message message = new Message();
            message.setSender("服务器");
            message.setContent(news);
            message.setSendTime(new Date().toString());
            message.setType(MessageType.MESSAGE_EVERYONE);
            System.out.println("服务器推送消息给所有人" + news);

            // 遍历当前所有在线线程，得到socket并转发message
            String onlineUser = ManageServerConnectServiceThread.getOnlineUser();
            String[] onlineUsers = onlineUser.split(" ");
            for (String user : onlineUsers) {
                ServerConnectionThread serverConnectionThread = ManageServerConnectServiceThread.get(user);
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(serverConnectionThread.getSocket().getOutputStream());
                    objectOutputStream.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } // for
        }

    }
}
